/*
 * Copyright (c) MengChang Wang <wangmengchang@gmail.com>
 * Webpage:  http://www.journalhome.com/texpen/
 *
 *
*/

#include "headers/mainwindow.h"
#include <QProcess>
#include <QAction>
#include <QTextDocument>
#include <QTextCursor>
#include <QVector>
#include <QTextCursor>
#include <QDebug>

#include <QCompleter>
#include <QListWidget>
#include <QFontMetrics>


//To-Do
// Scan Labels , and listen to "\ref{"

QStringList AutoCompList;

void MainWindow::showCompletion(){
    if(AutoCompList.isEmpty()){
        AutoCompList<<"document"<<"usepackage"<<"section"<<"subsection"<<"subsubsection"<<"chapter"
                   <<"documentclass"<<"graphicx"<<"fontspec"<<"newcommand"<<"renewcommand"
                  <<"tableofcontents"<<"itemize"<<"item"
                  <<"article"<<"book"<<"begin"<<"end"<<"equation"<<"table"<<"figure"
                   <<"alpha"<<"beta"<<"gamma"<<"delta"<<"epsilon"<<"zeta"<<"eta"
                                   <<"theta"<<"iota"<<"kappa"<<"lambda"
                                 <<"rho"<<"sigma"<<"tau"<<"upsilon"<<"phi"<<"chi"
                                 <<"psi"<<"omega"<<"varGamma"<<"varSigma"<<"varTheta"
                                 <<"varLambda"<<"varkappa"<<"varpi"<<"varsigma"
                                <<"varepsilon"<<"varOmega"<<"emptyset"<<"square"
                               <<"sum"<<"notin"<<"leq"<<"geq"<<"equiv"<<"sin"<<"cos"
                                            <<"frac"<<"ldots"<<"sim"<<"text"<<"prod"<<"cdot"
                                            <<"infty"<<"limits"<<"nonumber"<<"forall"<<"cup"<<"wedge"
                                            <<"left"<<"right"<<"lfloor"<<"rfloor"<<"lceil"<<"rceil"
                                            <<"mathcal"<<"max"<<"min"<<"int"<<"times"<<"cap"
                                           <<"mathop"<<"sup"<<"leftarrow"<<"rightarrow"<<"exp"
                                          <<"Rightarrow"<<"Leftarrow"<<"bar"<<"hat"<<"tilde"
                 <<"TeXpen"
                 <<"MengChang Wang";
    }
    comSec="";

    autoComp->clear();
    autoComp->hide();

    QTextCursor cr = TextEdit->textCursor(); //cr.positionInBlock()
    int st = cr.positionInBlock()-50;
    int ed = cr.positionInBlock();
    if(st<0){st=0;}
    QString sec = cr.block().text().mid(st,ed-st);
    if(sec.endsWith("?") ||sec.endsWith(",") || sec.endsWith(".") || sec.endsWith(" ")  || sec.endsWith(":")
            || sec.endsWith("/")|| sec.endsWith("&")  || sec.endsWith("\%") || sec.endsWith("-")
            ){
        autoComp->clear();
        autoComp->hide();
        TextEdit->setFocus();
        return;
    }
    int spidx = sec.indexOf(QRegExp("\\s|\\t|\\{|\\}|\\(|\\)|\\\\"));
    int pos =0 ;
    while(spidx >= 0){
        pos = spidx+1;
        spidx = sec.indexOf(QRegExp("\\s|\\t|\\{|\\}|\\(|\\)|\\\\"), pos);
    }
    sec = sec.mid(pos);
    if(sec.isEmpty() || sec.length()<2){
        return;
    }
    QRect rt = TextEdit->cursorRect();
    comSec=sec;

    QStringList cl;
    QStringList el;

    int ml = 0;
    QString maxstr ="";
    foreach (QString wd, AutoCompList){
        if(wd == sec){
            cl<<wd;
            if(wd.length() > ml){ml = wd.length();maxstr=wd;}
        }
        else if(wd.startsWith(sec)){
            el<<wd;
            if(wd.length() > ml){ml = wd.length();maxstr=wd;}
        }
    }
    cl<<el;

    if(cl.isEmpty()){
        autoComp->clear();
        autoComp->hide();
        TextEdit->setFocus();
        return;
    }
    int h = (cl.size()>10)?10:cl.size();

    QFontMetrics fm(Settings.Font);
    //int ww = fm.maxWidth(); if(ww>25){ww=fm.width('W');}qDebug()<<"www="<<ww<<endl;
    int hh = fm.height();
    int W= fm.width(maxstr)+20;//ww *(ml+2)  + 20;
    int H= hh *(h+0)  + 10;

    int Top = 0;
    int Left = 0;

    autoComp->setFont(Settings.Font);

    autoComp->clear();
    autoComp->addItems(cl);
    if(rt.bottom()+1 + H <= TextEdit->height()){
        Top = rt.bottom()+1;
    }else{
        Top = rt.top()-1-H;
    }
    if(rt.left()+W > TextEdit->width()){
        Left = TextEdit->width()-W;
    }else{
        Left = rt.left();
    }
    autoComp->setGeometry(Left,Top,W,H);
    autoComp->setCurrentRow(0);
    statusBar()->showMessage(tr("Key [space]: first item; Or Up/Down(or [Tab] then J/K/Up/Down), then [space]."));
    autoComp->show();
    TextEdit->setFocus();
}

void MainWindow::completeWith(QString txt){

    QTextCursor cr = TextEdit->textCursor();
    if(comSec == txt){
        cr.insertText(" ");
        return;
    }

    int l=comSec.length();

    for(int i=0;i<l;i++){
        cr.deletePreviousChar();
    }
    cr.insertText(txt);
    TextEdit->setFocus();
    autoComp->clear();
    autoComp->hide();
    statusBar()->showMessage(tr(""));
}

